/**
 * Performs an XMLHttpRequest to Retailigence API to get product information.
 * @param callback Function If the response from fetching url has a
 *     HTTP status of 200, this function is called with a JSON decoded
 *     response.  Otherwise, this function is called with null.
 */
function fetchRetailigence(keyword, zip, callback) {
    // Note that any URL fetched here must be matched by a permission in
    // the manifest.json file!
    var url = 'http://apitest.retailigence.com/v1.2/products?apikey=7OakAFAr-I4r1SG0IuoU_s6BSyoOpJNw&format=json&zip=' + zip + '&keywords=' + keyword;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(data) {
	if (xhr.readyState == 4) {
            if (xhr.status == 200) {
		var data = JSON.parse(xhr.responseText);
		callback(data);
            } else {
		callback(null);
            }
	}
    }
    xhr.open('GET', url, true);
    xhr.send();
};

/**
 * Parses text from Retailigence API and generates content.
 * @param data Object JSON decoded response.  Null if the request failed.
 */
function onText(data) {
    var results_dom = document.createElement('ol');
    for (var i in data.RetailigenceSearchResult.results) {
	var product = data.RetailigenceSearchResult.results[i].SearchResult.product;
	var location = data.RetailigenceSearchResult.results[i].SearchResult.location;
	var productImgSrc = '';
	var productLink = product.url;
	var productName = product.name;
	var productPrice = product.msrpCurrency + ': ' + product.msrp;
	var productAddress = [location.name, location.address.address1,
			      location.address.city, location.address.state].join(', ');
	var productSnippet = product.descriptionShort ? product.descriptionShort : '';
	for (var j in product.images) {
	    if (product.images[j].ImageInfo.imageName == 'SMALL') {
		productImgSrc = product.images[j].ImageInfo.link;
		break;
	    }
	}

	var one_res = ['<div class="pslicont">',
		       '  <div class="psliimg">',
		       '    <a href="' + productImgSrc + '">',
		       '      <img src="' + productImgSrc + '" height=60 width=60 class="th">',
		       '    </a>',
		       '  </div>',
		       '  <div class="pslimain">',
		       '    <h3 class="r">',
		       '      <a href="' + productLink + '">' + productName + '</a>',
		       '    </h3>',
		       '    <div class="f kb">' + productPrice + '</div>',
		       '    <div class="f kb">' + productAddress + '</div>',
		       '    <div class="st">' + productSnippet + '</div>',
		       '  </div>',
		       '</div>'].join('');

	var result_dom = document.createElement('li');
	result_dom.innerHTML = one_res;
	result_dom.setAttribute('class', 'g psli knavi');
	results_dom.appendChild(result_dom);
    } 
   
    // Create the overlay at the top of the page and fill it with data.
    var res = document.getElementById('rso');
    res.insertBefore(results_dom, res.firstChild);
};

var querybox = document.getElementById('lst-ib');
if (querybox) {
    var keyword = escape(querybox.value);
    var zip = 94043;
    var loc = document.getElementById('pslocdisp');
    var re = /\ (\d+)\ \-\ /;
    var match = re.exec(loc.innerHTML);
    if (match) {
	zip = match[1];
    }
    fetchRetailigence(keyword, zip, onText);
}
